package com.hig.onlineexam.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hig.exam.domain.ExamTaskManager;
import com.hig.exam.service.IExamTaskManagerService;
import com.hig.onlineexam.domain.ExamTaskAnswer;
import com.hig.onlineexam.domain.dto.ExamQuestionsContentData;
import com.hig.onlineexam.domain.dto.SubmitDto;
import com.hig.onlineexam.service.IExamTaskAnswerService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.hig.onlineexam.domain.ExamFinishAnswer;
import com.hig.onlineexam.service.IExamFinishAnswerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考试成绩Controller
 * 
 * @author qnsdt
 * @date 2023-02-24
 */
@RestController
@RequestMapping("/onlineexam/finishanswer")
@Api("考试结束相关接口")
public class ExamFinishAnswerController extends BaseController
{
    @Autowired
    private IExamFinishAnswerService examFinishAnswerService;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;
    /**
     * 查询考试成绩列表
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:finishanswer:list')")
    @GetMapping("/list")

    public TableDataInfo list(ExamFinishAnswer examFinishAnswer)
    {
        startPage();
        List<ExamFinishAnswer> list = examFinishAnswerService.selectExamFinishAnswerList(examFinishAnswer);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('onlineexam:finishanswer:list')")
    @GetMapping("/listNoPage")
    public TableDataInfo listNoPage()
    {
        startPage();
        List<ExamFinishAnswer> list = examFinishAnswerService.selectExamFinishAnswerList(null);
        return getDataTable(list);
    }
    /**
     * 导出考试成绩列表
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:finishanswer:export')")
    @Log(title = "考试成绩", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ExamFinishAnswer examFinishAnswer)
    {
        List<ExamFinishAnswer> list = examFinishAnswerService.selectExamFinishAnswerList(examFinishAnswer);
        ExcelUtil<ExamFinishAnswer> util = new ExcelUtil<ExamFinishAnswer>(ExamFinishAnswer.class);
        return util.exportExcel(list, "考试成绩数据");
    }

    /**
     * 获取考试成绩详细信息
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:finishanswer:query')")
    @GetMapping(value = "/{examCode}")
    public AjaxResult getInfo(@PathVariable("examCode") String examCode)
    {
        return AjaxResult.success(examFinishAnswerService.selectExamFinishAnswerById(examCode));
    }

    /**
     * 新增考试成绩
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:finishanswer:add')")
    @Log(title = "考试成绩", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamFinishAnswer examFinishAnswer)
    {
        return toAjax(examFinishAnswerService.insertExamFinishAnswer(examFinishAnswer));
    }
    @Autowired
    IExamTaskAnswerService examTaskAnswerService;

    @Autowired
    private IExamTaskManagerService examTaskManagerService;
    /**
     * 维护考试成绩
     */
    @PostMapping("/save")
    @ApiOperation("交卷")

    public AjaxResult save(@RequestBody ExamFinishAnswer examFinishAnswer)
    {

    	System.out.println("examFinishAnswer:" + examFinishAnswer.toString());
//        String examCode = examFinishAnswer.getExamCode();
//        ExamTaskManager examTaskManager = examTaskManagerService.selectExamTaskManagerById(examCode);
//        if (ObjectUtil.isNull(examTaskManager)){
//            throw new RuntimeException("查询不到考试信息");
//        }
//        String buildType = examTaskManager.getBuildType();
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        Long userId = loginUser.getUser().getUserId();
//        if ("3".equals(buildType)){
//            //随机打乱顺序
//            String questionsCode = examFinishAnswer.getQuestionsCode();
//            Map<String, Object> cacheMap = redisCache.getCacheMap(examCode + questionsCode + userId);
//            if (ObjectUtil.isNotNull(cacheMap)){
//                String questionsAnswer = examFinishAnswer.getQuestionsAnswer();
//                String o = (String) cacheMap.get(questionsAnswer);
//                examFinishAnswer.setQuestionsAnswer(o);
//            }
//        }


        return toAjax(examFinishAnswerService.intoExamFinishAnswer(examFinishAnswer));
    }
    @PostMapping("/submit")
    @ApiOperation("交卷/v2")

    public AjaxResult submit(@RequestBody SubmitDto submitDto)
    {
        ExamFinishAnswer examFinishAnswer = submitDto.getExamFinishAnswer();
        String examCode = examFinishAnswer.getExamCode();
        ExamTaskManager examTaskManager = examTaskManagerService.selectExamTaskManagerById(examCode);
        if (ObjectUtil.isNull(examTaskManager)){
            throw new RuntimeException("查询不到考试信息");
        }
        String buildType = examTaskManager.getBuildType();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();


        List<ExamTaskAnswer> answers = submitDto.getAnswers();
//        if (CollectionUtil.isEmpty(answers)){
//            throw new RuntimeException("未提交答题数据");
//        }
        if (CollectionUtil.isNotEmpty(answers)){
            for (ExamTaskAnswer answer : answers) {

                if ("3".equals(buildType)){
                    //随机打乱顺序
                    String questionsCode = answer.getQuestionsCode();
                    Map<String, Object> cacheMap = redisCache.getCacheMap(examCode + questionsCode + userId);
                    if (ObjectUtil.isNotNull(cacheMap)){
                        String questionsAnswer = answer.getQuestionsAnswer();
                        Long questionsType = answer.getQuestionsType();
                        if (questionsType!=3){
                            String o = (String) cacheMap.get(questionsAnswer);
                            answer.setQuestionsAnswer(o);
                        }else {
                            if (StringUtils.isNotBlank(questionsAnswer)){
                                String[] split = questionsAnswer.split(",");
                                ArrayList<String> list = new ArrayList<>();
                                for (String s : split) {
                                    String o = (String) cacheMap.get(s);
                                    list.add(o);
                                }
// 对选项进行排序
                                list.sort(String::compareTo); // 默认按照字母顺序排序

// 拼接成 A,B,C,D 格式
                                String result = String.join("", list);
                                answer.setQuestionsAnswer(result);
                            }

                        }

                    }
                }
                answer.setUserCode(examFinishAnswer.getUserCode());
                examTaskAnswerService.insertExamTaskAnswer(answer);
            }

        }

        System.out.println("examFinishAnswer:" + examFinishAnswer.toString());
        return toAjax(examFinishAnswerService.intoExamFinishAnswer(examFinishAnswer));
    }
    /**
     * 修改考试成绩
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:finishanswer:edit')")
    @Log(title = "考试成绩", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExamFinishAnswer examFinishAnswer)
    {
        return toAjax(examFinishAnswerService.updateExamFinishAnswer(examFinishAnswer));
    }

    /**
     * 删除考试成绩
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:finishanswer:remove')")
    @Log(title = "考试成绩", businessType = BusinessType.DELETE)
	@DeleteMapping("/{examCodes}")
    public AjaxResult remove(@PathVariable String[] examCodes)
    {
        return toAjax(examFinishAnswerService.deleteExamFinishAnswerByIds(examCodes));
    }
}
